<template>
	<el-card shadow="hover">
		<el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch">
			<el-form-item label="用户ID" prop="user_id">
				<el-select
					v-model="queryParams.user_id"
					filterable
					remote
					clearable
					placeholder="请输入选择用户"
					:remote-method="userIdRemoteMethod"
					:loading="userIdLoading"
					@focus="onUserIdFocus"
				>
					<el-option v-for="item in userIdOptions" :key="item.id" :label="item.nickname" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="排序方式" prop="sort">
				<el-select v-model="queryParams.sort">
					<el-option label="正序" value="asc" />
					<el-option label="倒序" value="desc" />
				</el-select>
			</el-form-item>
			<el-form-item label="日期" prop="date" v-if="queryParams.type == 'date'">
				<el-date-picker v-model="queryParams.date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期"> </el-date-picker>
			</el-form-item>
			<el-form-item label="周期" prop="week" v-if="queryParams.type == 'week'">
				<el-date-picker
					v-model="queryParams.week"
					type="week"
					:format="queryParams.start_time + ' ~ ' + queryParams.ent_time"
					@change="onChangeWeek"
					placeholder="选择周期"
				>
				</el-date-picker>
			</el-form-item>
			<el-form-item label="月份" prop="month" v-if="queryParams.type == 'month'">
				<el-date-picker v-model="queryParams.month" type="month" value-format="YYYY-MM" placeholder="选择月份"> </el-date-picker>
			</el-form-item>
			<el-form-item label="年份" prop="year" v-if="queryParams.type == 'year'">
				<el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" placeholder="选择年份"> </el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="onQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="onResetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="top-block mb8">
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" @click="onExport"> 导出 </el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
		</el-row>
		<el-tabs type="border-card" @tab-click="onSwitchTab" v-model="queryParams.type">
			<el-tab-pane label="全部" name="all" />
			<el-tab-pane label="日统计" name="date" />
			<el-tab-pane label="周统计" name="week" />
			<el-tab-pane label="月统计" name="month" />
			<el-tab-pane label="年统计" name="year" />
		</el-tabs>
		<el-table :data="tableList" v-loading="loading">
			<el-table-column label="ID" align="center" prop="id" key="8" />
			<el-table-column label="用户" align="center" prop="nickname" key="9" />
			<el-table-column label="用户ID" align="center" prop="user_id" key="10" />
			<template v-if="queryParams.type != 'all'">
				<el-table-column label="年份" align="center" prop="year" key="11" v-if="queryParams.type == 'year'" />
				<el-table-column label="月份" align="center" prop="month" key="12" v-if="queryParams.type == 'month'" />
				<el-table-column label="日期" align="center" prop="date" key="13" v-if="queryParams.type == 'date'" />
			</template>
			<template v-if="queryParams.type == 'week'">
				<el-table-column label="开始时间" align="center" prop="start_time" key="14" />
				<el-table-column label="结束时间" align="center" prop="ent_time" key="15" />
			</template>
			<el-table-column label="金额" align="center" prop="amount" key="16" />
			<el-table-column label="金额(退款)" align="center" prop="amount_sub" key="17" />
		</el-table>
		<pagination-component
			v-show="total > 0"
			:total="total"
			v-model:page="queryParams.pageNum"
			v-model:limit="queryParams.pageSize"
			@pagination="getList"
		/>
	</el-card>
</template>

<script lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { handleDownloadByName } from '/@/utils/utils';
import { userStatisticsApi, orderSelectUsers } from '/@/api/admin1';
import { ElLoading } from 'element-plus';

const UserStatisticsApi = userStatisticsApi();

export default {
	name: 'consumeStatistics',
	setup() {
		const state = reactive({
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				type: 'all', // all date week month year
				user_id: '', // 用户id
				sort: 'asc', // 类型 正序 :asc  倒序：desc
				date: '', // 日统计搜索
				week: '', // 周统计-周期
				start_time: '', // 周统计-开始时间（只能选7天。周一至周日）
				ent_time: '', // 周统计-结束时间（只能选7天。周一至周日）
				month: '', // 月统计-月份 2023-10
				year: '', // 年统计-年份 2023
			},
			userIdLoading: false,
			userIdOptions: [] as any,
			showSearch: true,
			tableList: [],
			loading: false,
			total: 0,
		});
		let start_page: number = 1; // 导出页数
		let start_page_total: number = 1; // 导出总页数
		const queryFormRef = ref(null);
		const loadingDownloadRef = ref(null);

		onMounted(() => {
			getList();
		});

		/********** 点击事件 **********/
		// 选择用户
		const onUserIdFocus = () => {
			if (!state.queryParams.user_id) {
				state.userIdLoading = true;
				_orderSelectUsers({ type: 0 });
			}
		};
		// 搜索
		const onQuery = () => {
			state.queryParams.pageNum = 1;
			getList();
		};
		// 重置
		const onResetQuery = () => {
			state.queryParams.date = '';
			state.queryParams.month = '';
			state.queryParams.year = '';
			state.queryParams.week = '';
			state.queryParams.start_time = '';
			state.queryParams.ent_time = '';
			(queryFormRef.value as any)?.resetFields();
			onQuery();
		};
		// 切换tab
		const onSwitchTab = () => {
			state.queryParams.pageNum = 1;
			getList();
		};
		// 导出
		const onExport = () => {
			(loadingDownloadRef.value as any) = ElLoading.service({
				lock: true,
				text: '正在导出，请耐心等待...',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			switch (state.queryParams.type) {
				case 'all':
					_usersSalesTotalExport({
						...state.queryParams,
						start_page: 1,
					});
					break;
				case 'date':
					_usersSalesDateExport({
						...state.queryParams,
						start_page: 1,
					});
					break;
				case 'week':
					_usersSalesWeekExport({
						...state.queryParams,
						start_page: 1,
					});
					break;
				case 'month':
					_usersSalesMonthExport({
						...state.queryParams,
						start_page: 1,
					});
					break;
				case 'year':
					_usersSalesYearExport({
						...state.queryParams,
						start_page: 1,
					});
					break;
				default:
					break;
			}
		};

		/********** 方法事件 **********/
		// 时间戳转为yy-mm-dd
		const getCurrentTime = (data: any, num: any) => {
			let date = new Date(data);
			const Y = date.getFullYear();
			const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
			const D = date.getDate() + num < 10 ? '0' + (date.getDate() + num) : date.getDate() + num;
			let _date = Y + '-' + M + '-' + D;
			return _date;
		};
		// 改变周期
		const onChangeWeek = (val: any) => {
			const date = new Date(val);
			const y = date.getFullYear();
			const m = date.getMonth();
			const d = date.getDate();
			const week = date.getDay();
			const start = new Date(y, m, d - week + 1);
			const end = new Date(y, m, d - week + 7);
			state.queryParams.start_time = getCurrentTime(start, 0);
			state.queryParams.ent_time = getCurrentTime(end, 0);
		};
		// 列表
		const getList = () => {
			state.loading = true;
			switch (state.queryParams.type) {
				case 'all':
					_usersSalesTotalList(state.queryParams);
					break;
				case 'date':
					_usersSalesDateList(state.queryParams);
					break;
				case 'week':
					_usersSalesWeekList(state.queryParams);
					break;
				case 'month':
					_usersSalesMonthList(state.queryParams);
					break;
				case 'year':
					_usersSalesYearList(state.queryParams);
					break;
				default:
					break;
			}
		};
		// 搜索用户
		const userIdRemoteMethod = (query: string) => {
			if (query) {
				state.userIdLoading = true;
				_orderSelectUsers({ nickname: query, type: 0 });
			}
		};
		/********** 网络请求 **********/
		// 选择用户(搜索)
		const _orderSelectUsers = (_data: any) => {
			orderSelectUsers(_data)
				.then((res: any) => {
					console.log('选择用户(搜索)', res);
					state.userIdOptions = res.data.list;
					state.userIdLoading = false;
				})
				.catch(() => {
					state.userIdLoading = false;
				});
		};
		// 总统计列表
		const _usersSalesTotalList = (_data: any) => {
			UserStatisticsApi.usersSalesTotalList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 日统计列表
		const _usersSalesDateList = (_data: any) => {
			UserStatisticsApi.usersSalesDateList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 周统计列表
		const _usersSalesWeekList = (_data: any) => {
			UserStatisticsApi.usersSalesWeekList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 月统计列表
		const _usersSalesMonthList = (_data: any) => {
			UserStatisticsApi.usersSalesMonthList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 年统计列表
		const _usersSalesYearList = (_data: any) => {
			UserStatisticsApi.usersSalesYearList(_data)
				.then((res: any) => {
					state.tableList = res.data.list;
					state.total = res.data.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		};
		// 导出总统计
		const _usersSalesTotalExport = (_data: any) => {
			if (start_page <= start_page_total) {
				UserStatisticsApi.usersSalesTotalExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '用户消费总统计导出', false);
						_usersSalesTotalExport({ start_page: 1, ..._data });
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};
		// 导出日统计
		const _usersSalesDateExport = (_data: any) => {
			if (start_page <= start_page_total) {
				UserStatisticsApi.usersSalesDateExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '用户消费日统计导出', false);
						_usersSalesDateExport({ start_page: 1, ..._data });
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};
		// 导出周统计
		const _usersSalesWeekExport = (_data: any) => {
			if (start_page <= start_page_total) {
				UserStatisticsApi.usersSalesWeekExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '用户消费周统计导出', false);
						_usersSalesWeekExport(_data);
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};
		// 导出月统计
		const _usersSalesMonthExport = (_data: any) => {
			if (start_page <= start_page_total) {
				UserStatisticsApi.usersSalesMonthExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '用户消费月统计导出', false);
						_usersSalesMonthExport(_data);
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};
		// 导出年统计
		const _usersSalesYearExport = (_data: any) => {
			if (start_page <= start_page_total) {
				UserStatisticsApi.usersSalesYearExport(_data)
					.then((res: any) => {
						start_page == 1 && (start_page_total = res.data.info.count_page);
						start_page++;
						handleDownloadByName(res.data.info.url, '用户消费年统计导出', false);
						_usersSalesYearExport(_data);
						if (start_page >= start_page_total) {
							(loadingDownloadRef.value as any)?.close();
							start_page = 1;
							start_page_total = 1;
						}
					})
					.catch(() => {
						(loadingDownloadRef.value as any)?.close();
						start_page = 1;
						start_page_total = 1;
					});
			}
		};

		return {
			queryFormRef,
			onChangeWeek,
			getList,
			onExport,
			onQuery,
			onResetQuery,
			onSwitchTab,
			userIdRemoteMethod,
			onUserIdFocus,
			...toRefs(state),
		};
	},
};
</script>

<style scoped></style>
